const axios = require('axios').default
const OSS = require('ali-oss')
const fs = require('fs')
const dayjs = require('dayjs');
const base64 = require('../base64');
const oss = new OSS({
    accessKeyId: "LTAI5tGUK2ucD5xtyPd86f9k",
    accessKeySecret: "PcQKwHF6Fr4T7XnDjLxMkgIrDoiIpq",
    bucket: "happy-art",
    region: "oss-cn-shenzhen",
    endpoint: "oss-cn-shenzhen.aliyuncs.com",
  });
const uploadFiles = async (images,id)=>{
    const files = []
    for(let i=0;i<images.length;i++){
        const fileName = `text2image/${dayjs().format('YYYY-MM-DD')}/${id}-${i}.png`
        // fs.writeFileSync('./t'+i+'.txt',images[i])
        const buffer = Buffer.from(images[i], 'base64');

       await oss.put(fileName,buffer);
       files.push(fileName)
    }
   
    return files.join(',')
}

const action = (item)=>{
    console.log('actions',item)
   return new Promise((resolve)=>{
            axios({
                timeout:99999999,
                // url:`http://172.20.21.185:7860/sdapi/v1/txt2img`,
                url:`http://127.0.0.1:7860/sdapi/v1/txt2img`,
                method:'POST',
                data:JSON.parse(item.params)
            }).then(res=>res.data).then( async res=>{
                const {images = []} = res
               const files = await uploadFiles(images,item.id)
                // oss
                // const fileName = `${md5}${path.extname(file.filepath)}`;
                // const name = `www/resource/${fileName}`;
                // const result = await oss.put(name, file.filepath);
                
                console.log('resssss',res);
                resolve(files);

                
            }).catch((err)=>{
                console.error('error',err)
            })
   }) 
}
module.exports = action